package cn.edu.buaa.treehole.service;

import cn.edu.buaa.treehole.dao.PostTagDao;
import cn.edu.buaa.treehole.dao.TagDao;
import cn.edu.buaa.treehole.pojo.dao.TagDaoInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class TagService {
    private final PostTagDao postTagDao;
    private final TagDao tagDao;

    @Autowired
    public TagService(PostTagDao postTagDao, TagDao tagDao) {
        this.postTagDao = postTagDao;
        this.tagDao = tagDao;
    }

    public synchronized long ensureTagOfName(String name) {
        List<TagDaoInfo> tags = tagDao.selectAllTag();
        for (TagDaoInfo tag : tags) {
            if (tag.getName().equals(name)) {
                return tag.getTid();
            }
        }
        Long max = tagDao.selectMaxTid();
        long tid = max == null ? 0 : max;
        TagDaoInfo tag = new TagDaoInfo();
        tag.setDescription(name);
        tag.setName(name);
        tag.setTid(++tid);
        tagDao.insertTag(tag);
        return tid;
    }

    public Map<Long, String> getAllTagsForPid(long pid) {
        List<Long> tidList = postTagDao.selectAllTidByPid(pid);
        HashMap<Long, String> ret = new HashMap<>();
        for (long tid : tidList) {
            ret.put(tid, tagDao.selectTagByTid(tid).getName());
        }
        return ret;
    }

    public List<Long> getTidsByName(String name) {
        LinkedList<Long> result = new LinkedList<>();
        List<TagDaoInfo> tagInfos = tagDao.selectAllTag();
        for (TagDaoInfo tag : tagInfos) {
            if (tag.getName().contains(name)) {
                result.add(tag.getTid());
            }
        }
        return result;
    }

    public TagDaoInfo getTagByTid(long tid) {
        return tagDao.selectTagByTid(tid);
    }

    public void addTagsForPost(List<Long> tags, long pid) {
        for (long tag : tags) {
            postTagDao.insertLinkPidWithTid(pid, tag);
        }
    }

    public void deleteAllTagsForPost(long pid) {
        postTagDao.deleteAllByPid(pid);
    }

    public void deleteCertainTagForPost(long pid, long tid) {
        postTagDao.deleteCertain(pid, tid);
    }
}
